﻿using AutoMapper.Extensions.ExpressionMapping;
using BCCommon;
using BCService;
using BCService.TMS.PlatformManageFee.PlatformManageFeeConfig;
using BCService.TMS.PlatformManageFee.PlatformManageFeeExecutionPlan;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using TMSPlatformManageFeeExecutionPlanJob.Redis;

namespace TMSPlatformManageFeeExecutionPlanJob
{
    class Program
    {
        public static IServiceCollection services { get; set; }
        public static IConfiguration configuration { get; set; }
        static void Main(string[] args)
        {
            //设定定时执行
            SetTaskAtFixedTime();
            //Console.Readkey()保持Console窗口不关闭，否则，该程序执行后一闪就关闭，不会等1分钟的时间。
            Console.ReadKey();
        }

        private static void SetTaskAtFixedTime()
        {
            DateTime now = DateTime.Now;
            int executeDay = Convert.ToInt32(ConfigurationManager.AppSettings.Get("DayExecution"));
            int oneOClock = DateTime.Today.Day; 
            DateTime executeDate = DateTime.Today;
            if (oneOClock == executeDay && now > executeDate)
            {
                executeDate = DateTime.Today.AddMonths(1);
            }
            int msUntilFour = (int)((executeDate - now).TotalSeconds);

            
            var t = new System.Threading.Timer(TMSPlatformManageFeeExecutionPlan);
            t.Change(msUntilFour, Timeout.Infinite);
        }

        private static void TMSPlatformManageFeeExecutionPlan(object state)
        {
            Console.WriteLine("平台管理费执行计划处理开始");
            var builder = new ConfigurationBuilder();
#if DEBUG
            Console.WriteLine("DEBUG");
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
#else
            Console.WriteLine("RELEASE");
            builder.AddJsonFile("/mnt/web/config/appsettings.production.json", optional: true, reloadOnChange: true);
#endif
            configuration = builder.Build();
            GeneralContainer.Configuration = configuration;
            services = new ServiceCollection()
                .AddLogging()
                .AddScoped<ILoggerFactory, LoggerFactory>()
                .AddMySql(option =>
                {
                    option.MasterConnectionString = configuration["MySqlConnectionString"];
                    option.SlaveConnectionString = configuration["MySqlConnectionString"];
                })
                .AddRedis(options =>
                {
                    if (bool.TryParse(configuration["EnableRedis"], out bool enableRedis))
                    {
                        options.EnableRedis = enableRedis;
                    }
                    options.RedisConnectionString = configuration["RedisConnectionString"];
                    options.RedisDatabaseNo = configuration["RedisDatabaseNo"];
                })
                .AddScoped<IApplicationContextService, ConsoleContextService>()
                .AddServices()
                .AddMapperConfiguration();

            #region 模型映射
            var mappingConfiguration = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.AddMaps(Assembly.Load(new AssemblyName("BCService")));
                cfg.AddExpressionMapping();
            });
            mappingConfiguration.CompileMappings();
            BCService.Utils.MapperExtension.Mapper = mappingConfiguration.CreateMapper();

            var workflowConfiguration = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.AddMaps(Assembly.Load(new AssemblyName("BCWorkflowEngine")));
                cfg.AddExpressionMapping();
            });
            workflowConfiguration.CompileMappings();

            BCWorkflowEngine.Utils.MapperExtension.Mapper = workflowConfiguration.CreateMapper();
            #endregion

            services.AddSingleton(typeof(IConfiguration), configuration);
            Console.WriteLine("Service Count:" + services.Count);
            IServiceProvider serviceProvider = services.BuildServiceProvider(new ServiceProviderOptions().ValidateScopes);
            //ILoggerFactory loggerFactory = serviceProvider.GetService<ILoggerFactory>().AddConsole(LogLevel.Debug);
            //全局服务提供
            GeneralContainer.ServiceProvider = serviceProvider;
            IDatabaseContext databaseContext = serviceProvider.GetService<IDatabaseContext>();
            IPlatformManageFeeExecutionPlanService platformManageFeeExecutionPlanService = serviceProvider.GetService<IPlatformManageFeeExecutionPlanService>();
            IPlatformManageFeeConfigService platformManageFeeConfigService = serviceProvider.GetService<IPlatformManageFeeConfigService>();
            Console.WriteLine("平台管理费执行计划处理服务完成");
            try
            {
                Console.WriteLine("开始调用处理程序");
                var notDoneList = platformManageFeeExecutionPlanService.GetNotDoneList();
                if (notDoneList.Any())
                {
                    foreach (var item in notDoneList)
                    {
                        databaseContext.BeginTransaction();
                        platformManageFeeExecutionPlanService.UpdateIsDone(item.PlatformManageFeeExecutionPlanId);
                        platformManageFeeConfigService.UpdateCurrentlyPlanId(item.PlatformManageFeeExecutionPlanId, item.SubAgentRecordId, item.ManageFeeBusinessType, item.ManageFeeRatio);
                        databaseContext.Commit();
                    }
                }
                Console.WriteLine("完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Log(JsonConvert.SerializeObject(ex));
            }
            SetTaskAtFixedTime();
        }

        private static void Log(string message)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());

            FileInfo fileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, "TMSWorkflowConsoleError_SpecificForm", DateTime.Now.ToString("yyyy-MM-dd") + ".txt").ToString());

            if (!Directory.Exists(Path.Combine(directoryInfo.FullName, "TMSWorkflowConsoleError_SpecificForm")))
            {
                Directory.CreateDirectory(Path.Combine(directoryInfo.FullName, "TMSWorkflowConsoleError_SpecificForm"));
            }

            try
            {
                if (!fileInfo.Exists)
                {
                    using (StreamWriter sw = fileInfo.CreateText())
                    {
                        sw.WriteLine("*****************************************");
                        sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());

                        sw.WriteLine("{0}", message);

                        sw.WriteLine();
                    }
                }
                else
                {
                    using (StreamWriter sw = fileInfo.AppendText())
                    {
                        sw.WriteLine("*****************************************");
                        sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());

                        sw.WriteLine("{0}", message);

                        sw.WriteLine();
                    }
                }
            }
            catch (Exception e)
            {
                using (StreamWriter sw = fileInfo.AppendText())
                {
                    sw.WriteLine("*****************************************");
                    sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                    sw.WriteLine("构建失败:");
                    sw.WriteLine("{0}", message);

                }
            }
        }
    }
}
